<template>
  <div class="code">
    <canvas ref="canvas" :width="width" :height="height"></canvas>
  </div>
</template>

<script>
import { onMounted, ref, watch } from "vue";
export default {
  props: {
    width: {
      type: String,
      default: "100",
    },
    height: {
      type: String,
      default: "30",
    },
    safecode: {
      type: String,
      required: true
    },
  },
  setup(props) {
    const canvas = ref(null);

    onMounted(() => {      
      watch(props, () => {
        draw();
      });
    });
    
    const draw = () => {
      var canvas_width = props.width;
      var canvas_height = props.height;
      var context = canvas.value.getContext("2d");

      for (var i = 0; i < 4; i++) {
        var deg = Math.random() - 0.5;
        const txt = props.safecode[i];
        var x = 10 + i * 20;
        var y = 20 + Math.random() * 8;
        context.font = "bold 23px 微软雅黑";

        context.translate(x, y);
        context.rotate(deg);

        context.fillStyle = randomColor();
        context.fillText(txt, 0, 0);

        context.rotate(-deg);
        context.translate(-x, -y);
      }
      for (var i = 0; i <= 5; i++) {
        context.strokeStyle = randomColor();
        context.beginPath();
        context.moveTo(
          Math.random() * canvas_width,
          Math.random() * canvas_height
        );
        context.lineTo(
          Math.random() * canvas_width,
          Math.random() * canvas_height
        );
        context.stroke();
      }
      for (var i = 0; i <= 30; i++) {
        context.strokeStyle = randomColor();
        context.beginPath();
        var x = Math.random() * canvas_width;
        var y = Math.random() * canvas_height;
        context.moveTo(x, y);
        context.lineTo(x + 1, y + 1);
        context.stroke();
      }
    }
    const randomColor = () => {
      var r = Math.floor(Math.random() * 256);
      var g = Math.floor(Math.random() * 256);
      var b = Math.floor(Math.random() * 256);
      return "rgb(" + r + "," + g + "," + b + ")";
    }

    return {
      canvas
    }
  },
};
</script>

<style scoped>
.input-val {
  width: 200px;
  height: 32px;
  border: 1px solid #ddd;
  box-sizing: border-box;
}
#canvas {
  vertical-align: middle;
  box-sizing: border-box;
  border: 1px solid #ddd;
  cursor: pointer;
}
.btn {
  display: block;
  margin-top: 20px;
  height: 32px;
  width: 100px;
  font-size: 16px;
}
</style>